﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace VBAConvertor.Parsers
{
    public static class ParserHelper
    {
        public const string DocumentParamName = "document";
        public const string AppVariableName = "app";

        public static string ResolveFunctionCall(string callExp)
        {
            return callExp;
        }

        private static readonly Regex VarPattern =
           new Regex(
               @"(?<refval>((ByRef)|(ByVal)) )?(?<var>[a-zA-Z_\$\d]+(\(\))?)((\s)+As(\s)+(?<type>[\w]+)((\s)+\*(\s)+(?<arrayLen>\d+))?)?",
               RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase | RegexOptions.Singleline);

        public static string GetVarDefs(string varDef, string varDefSeperator)
        {
            var variables = (from Match varMatch in VarPattern.Matches(varDef.Trim())
                             select varMatch).ToArray();

            var cSharpLine = new StringBuilder();

            for (var i = 0; i < variables.Length; i++)
            {
                var match = variables[i];

                var type = match.Groups["type"].Value;
                type = AdjustType(type);

                if (i > 0)
                {
                    cSharpLine.Append(varDefSeperator);
                    cSharpLine.Append(" ");
                    //cSharpLine.AppendLine();
                }

                if (!string.IsNullOrEmpty(match.Groups["refval"].Value))
                {
                    if (match.Groups["refval"].Value.StartsWith("ByRef"))
                    {
                        cSharpLine.Append("ref ");
                    }
                }

                cSharpLine.Append(type);
                if (!string.IsNullOrEmpty(match.Groups["arrayLen"].Value))
                {
                    cSharpLine.Append("[]");
                }
                cSharpLine.Append(" ");

                cSharpLine.Append(match.Groups["var"].Value);
            }
            
            return cSharpLine.ToString();
        }

        public static string AdjustType(string type)
        {
            if (string.IsNullOrEmpty(type))
            {
                type = "dynamic";
            }
            switch (type)
            {
                case "Integer":
                case "Long":
                    type = "int";
                    break;
                case "String":
                    type = "string";
                    break;
                case "Variant":
                    type = "dynamic";
                    break;
                case "Boolean":
                    type = "bool";
                    break;
            }
            return type;
        }
    }
}
